package com.example.ljdemo.infrastructure.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.UUID;

import static org.springframework.security.core.context.SecurityContextHolder.getContext;

/**
 * @author jingjing.dong
 * @since 2020/9/15-18:48
 */
@Slf4j(topic = "mybatis-auto-fill")
@Component // 一定不要忘记把处理器加到IOC容器中！
public class MyMetaObjectHandler implements MetaObjectHandler {
    // 插入时的填充策略
    @Override
    public void insertFill(MetaObject metaObject) {
        String currentUser = "crontask";
        Authentication authentication = getContext().getAuthentication();
        if (authentication != null) {
            currentUser = authentication.getName();
        }
        this.setFieldValByName("createTime", LocalDateTime.now(ZoneId.of("Asia/Shanghai")), metaObject);
        this.setFieldValByName("updateTime", LocalDateTime.now(ZoneId.of("Asia/Shanghai")), metaObject);
        this.setFieldValByName("uuid", UUID.randomUUID().toString(), metaObject);
        this.setFieldValByName("createBy", currentUser, metaObject);
    }

    // 更新时的填充策略
    @Override
    public void updateFill(MetaObject metaObject) {
        String currentUser = "crontask";
        Authentication authentication = getContext().getAuthentication();
        if (authentication != null) {
            currentUser = authentication.getName();
        }
        this.setFieldValByName("updateTime", LocalDateTime.now(ZoneId.of("Asia/Shanghai")), metaObject);
        this.setFieldValByName("updateBy", currentUser, metaObject);
    }
}